package com.dm.cloud.oauthlib.service.aop;

import cn.hutool.core.util.StrUtil;
import com.dm.cloud.core.config.CommonConstants;
import com.dm.cloud.core.service.user.CurrentUserService;
import com.dm.cloud.core.exception.CustomAuthException;
import com.dm.cloud.core.util.RequsetArrtibutesUtil;
import com.dm.cloud.oauthlib.service.anon.HasRole;
import com.dm.cloud.oauthlib.service.anon.IgnoreAuth;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;


@Aspect
@Component
public class OauthRoleAop {
    @Autowired
    private CurrentUserService currentUserService;
    @Pointcut("@annotation(com.dm.cloud.oauthlib.service.anon.HasRole)")
    public void hasRoleCut() {
    }

    @Before("hasRoleCut()")
    public void beforeAdvice(JoinPoint joinPoint) {
        if(AopUtil.getAnnotation(joinPoint, IgnoreAuth.class)!=null){
            return;
        }
        if(StrUtil.isEmpty(RequsetArrtibutesUtil.get(CommonConstants.AUTH_HEAD_KEY))){
            throw new CustomAuthException("用户未登录，请登录！");
        }
        HasRole roleAnno = AopUtil.getAnnotation(joinPoint, HasRole.class);
        if(!currentUserService.hasRoles(roleAnno.roles())){
            throw new CustomAuthException(roleAnno.errMsg());
        }
    }
}
